package cn.com.chinact.drools.demo.service.impl;

import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderError;
import org.kie.internal.builder.KnowledgeBuilderErrors;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.springframework.stereotype.Service;

import cn.com.chinact.drools.demo.domain.Message;
import cn.com.chinact.drools.demo.service.DroolsService;

@Service("droolsService")
public class DroolsServiceImpl implements DroolsService {

	@Override
	public String fireRule(int status, String mes) {

		//
		KieSession kSession = null;
		KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
		kbuilder.add(ResourceFactory.newFileResource("./target/classes/rules/Hello World.drl"), ResourceType.DRL);
		// 检查规则正确性
		KnowledgeBuilderErrors errors = kbuilder.getErrors();
		for (KnowledgeBuilderError error : errors) {
			System.out.println(("规则文件正确性有误：{" + error + "}"));
		}
		InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
		kBase.addPackages(kbuilder.getKnowledgePackages());

		// 执行规则
		kSession = kBase.newKieSession();

		// go !
		Message message = new Message();
		message.setMessage(mes);
		message.setStatus(status);
		kSession.insert(message);// 插入
		kSession.fireAllRules();// 执行规则
		kSession.dispose();
		return message.getMessage();
	}
}
